package sample.stock;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import sample.stock.model.YahooStock;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spannable;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class MyPortfolio extends Activity {
	private Button add = null;
	private Button refresh = null;
	private AutoCompleteTextView symbol = null;
	
	private ProgressDialog progressDialog;
	
	private static final String SOAP_ACTION = "http://www.webserviceX.NET/GetQuote";
	private static final String NAMESPACE = "http://www.webserviceX.NET/";
	private static final String METHOD_NAME = "GetQuote";
	private static final String URL = "http://www.webservicex.net/stockquote.asmx";
	
	@SuppressWarnings("unchecked")
	Map symbols = new HashMap<String, TableRow>();
	
	@SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myportfolio);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        add = (Button)findViewById(R.id.myPortfolioSubmitSymbol);
        add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				progressDialog = new ProgressDialog(MyPortfolio.this);
				progressDialog.setMessage("Loading...");
				new LoadStockTask(progressDialog).execute();
			}
		});
        
        
        refresh = (Button)findViewById(R.id.myPortfolioRefreshPortfolio);
        refresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        
        symbol = (AutoCompleteTextView)findViewById(R.id.myPortfolioSymbol);
        final ArrayAdapter adapterNASDAQ = ArrayAdapter.createFromResource(this, R.array.NASDAQ, R.layout.list_ticker);
        symbol.setAdapter(adapterNASDAQ);
        
    }
	
	private class LoadStockTask  extends AsyncTask<Void, Void, Void> {
	  	  private ProgressDialog progress;
	  	  private YahooStock stock = null;
	  	  
	  	  public LoadStockTask(ProgressDialog progress) {
	  		    this.progress = progress;
	  		  }
	
	  		  public void onPreExecute() {
	  		    progress.show();
	  		  }
	
	  		  @SuppressWarnings("unchecked")
			public void onPostExecute(Void unused) {
	  			  if(stock != null)
	  				symbols.put(stock.symbol, addStock(stock));
	  			  else
	  				  DisplayError();
	  			  if(progress.isShowing())
	  				  progress.dismiss();
	  		  }
	
			@SuppressWarnings("deprecation")
			@Override
	  		protected Void doInBackground(Void... arg0) {
				String sym = symbol.getText().toString();
	  				
	  			SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
	  			Request.addProperty("symbol", sym); // replace by selected ticker in spinner
	  		        
	  			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	  			soapEnvelope.dotNet = true;
	  			soapEnvelope.setOutputSoapObject(Request);
	  		        
	  			AndroidHttpTransport aht = new AndroidHttpTransport(URL);
	  			try{
	  				aht.call(SOAP_ACTION, soapEnvelope);
	  				SoapPrimitive responseResult = (SoapPrimitive)soapEnvelope.getResponse();
	  				stock  = ParseSoapResponse_Stock(responseResult);
	  			}catch (SocketTimeoutException e){
	  				progress.dismiss();
	  			}
	  			catch(Exception e){
	  			}
	  			return null;
	  		}
	}
	
	public void DisplayError()
	{
		TextView errorTextView = (TextView) findViewById(R.id.serviceError);
		errorTextView.setText("Service unreachable in a moment. Please try again later.");
		RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rlErrorMessage);
		relativeLayout.setVisibility(View.VISIBLE);
	}
	
	public TableRow addStock(final YahooStock s)
	{
		RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rlErrorMessage);
		relativeLayout.setVisibility(View.GONE);
		
		final TableLayout tableLayout = (TableLayout) findViewById(R.id.myPortfolioTable);
		final TableRow tableRow = new TableRow(this);
		final TextView myPortfolioSymbolLabel = new TextView(this);
		myPortfolioSymbolLabel.setId(1);
		myPortfolioSymbolLabel.setPadding(5, 5, 5, 5);
		myPortfolioSymbolLabel.setText(s.symbol,TextView.BufferType.SPANNABLE);
		Spannable str = (Spannable) myPortfolioSymbolLabel.getText();
		str.setSpan(new UnderlineSpan(), 0, symbol.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		myPortfolioSymbolLabel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent yahooView = new Intent(MyPortfolio.this, StockYahoo.class);
				yahooView.putExtra("symbol", s.symbol);
				startActivity(yahooView);
			}           
		});
		tableRow.addView(myPortfolioSymbolLabel);
		
		TextView myPortfolioSymbolValue = new TextView(this);
		myPortfolioSymbolValue.setId(2);
		myPortfolioSymbolValue.setPadding(5, 5, 5, 5);
		myPortfolioSymbolValue.setTextColor(Color.YELLOW);
		myPortfolioSymbolValue.setText(s.last);
		tableRow.addView(myPortfolioSymbolValue);
	
		ImageView myPortfolioSymbolChangeImage = new ImageView(this);
		myPortfolioSymbolChangeImage.setId(3);
		myPortfolioSymbolChangeImage.setPadding(5, 8, 5, 2);
		tableRow.addView(myPortfolioSymbolChangeImage);
		
		TextView myPortfolioSymbolChangeValue = new TextView(this);
		myPortfolioSymbolChangeValue.setId(4);
		myPortfolioSymbolChangeValue.setPadding(5, 5, 5, 5);
		myPortfolioSymbolChangeValue.setText(s.change);
		tableRow.addView(myPortfolioSymbolChangeValue);
		
		ImageView removeSymbolView = new ImageView(this);
		removeSymbolView.setPadding(5, 5, 5, 5);
		removeSymbolView.setImageResource(R.drawable.close_button);
		removeSymbolView.setOnClickListener(new View.OnClickListener() {
		public void onClick(View view) { 
			symbols.remove(s.symbol);
			tableRow.setVisibility(View.GONE);
			tableLayout.removeView(tableRow);
			setRowColor(tableLayout);
			}           
		});
		tableRow.addView(removeSymbolView);
		tableLayout.addView(tableRow);
		setRowColor(tableLayout);
		setChangeInformation(s, myPortfolioSymbolChangeValue, myPortfolioSymbolChangeImage);
		return tableRow;
	}
	
	private void setChangeInformation(YahooStock stockQuote, TextView textView, ImageView imageView) {
		String change = stockQuote.change;
		textView.setText(change);
		double changes = Double.parseDouble(change);
		if(changes >0){
			textView.setTextColor(Color.GREEN);
			imageView.setImageResource(R.drawable.green);
		}else if(changes<0){
			textView.setTextColor(Color.RED);
			imageView.setImageResource(R.drawable.red);
		}else{
			textView.setTextColor(Color.WHITE);
		}
	}
	
	private void setRowColor(final TableLayout tableLayout) {
		int childCount = tableLayout.getChildCount();
		for(int i=1;i<childCount;i++){
			TableRow iRow = (TableRow) tableLayout.getChildAt(i);
			if(i%2==0){
				iRow.setBackgroundColor(Color.parseColor("#333333"));
			}
			else{
				iRow.setBackgroundColor(Color.parseColor("#222222"));
			}
		}
	}

	public YahooStock ParseSoapResponse_Stock(SoapPrimitive result)
	{
		String temp = result.toString();
		
	  	YahooStock stock = new YahooStock();
	  	stock.symbol = temp.substring(temp.indexOf("<Symbol>")+8, 
	  			temp.indexOf("</Symbol>", temp.indexOf("<Symbol>")));
	  	stock.last = temp.substring(temp.indexOf("<Last>")+6, 
	  			temp.indexOf("</Last>", temp.indexOf("<Last>")));
	  	stock.change = temp.substring(temp.indexOf("<Change>")+8, 
	  			temp.indexOf("</Change>", temp.indexOf("<Change>")));
	  	stock.open = temp.substring(temp.indexOf("<Open>")+6, 
	  			temp.indexOf("</Open>", temp.indexOf("</Open>")));
		return stock;
	}
	}
